package com.company;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    static BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
    static ExecutorService executorService = Executors.newCachedThreadPool();
    static volatile Integer num = 1;

    public static void setQueue() throws Exception {
        queue.put("apple");
    }

    public static String getQueue() throws Exception {
        return queue.take();
    }

    public static Integer getSize() {
        return queue.size();
    }

    public static void main(String[] args) {
        testSet();
        testGet();


    }

    public static void testSet() {
        Runnable run = () -> {
            while (true) {
                // 生产苹果
                System.out.println("生产者准备生产苹果：" + num);
                try {
                    setQueue();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("生产完后有苹果：" + getSize() + "个");
                // 休眠300ms
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num++;
            }
        };
        executorService.submit(run);
    }

    public static void testGet() {
        Runnable run = () -> {
            try {
                while (true) {
                    // 消费苹果
                    try {
                        getQueue();
                        num--;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("消费完后有苹果：" + getSize() + "个");
                    // 休眠1000ms
                    Thread.sleep(1000);
                }
            } catch (InterruptedException ex) {
            }
        };
        executorService.submit(run);
    }
}
